const app = getApp()

Page({
    data: {
        username: '',
        password: '',
        studentId: '',
        email: '',
        phone: '',
        avatarUrl: '',
        isSubmitting: false
    },
    // 输入处理
    onInput(e) {
        const { field } = e.currentTarget.dataset
        this.setData({
            [field]: e.detail
        })
    },
    // 选择头像
    async chooseAvatar() {
        try {
            const res = await wx.chooseImage({
                count: 1,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            })

            wx.showLoading({ title: '上传中...' })

            // 上传头像
            const uploadRes = await this.uploadAvatar(res.tempFilePaths[0])
            
            this.setData({
                avatarUrl: uploadRes.data.url
            })

            wx.hideLoading()
        } catch (error) {
            console.error('选择/上传头像失败：', error)
            wx.hideLoading()
            wx.showToast({
                title: '上传头像失败',
                icon: 'none'
            })
        }
    },
    // 上传头像
    uploadAvatar(filePath) {
        return new Promise((resolve, reject) => {
            wx.uploadFile({
                url: `${app.globalData.baseUrl}/api/upload/register/avatar`,
                filePath,
                name: 'avatar',
                success: (res) => {
                    try {
                        const data = JSON.parse(res.data)
                        if (data.success) {
                            resolve(data)
                        } else {
                            reject(new Error(data.message))
                        }
                    } catch (error) {
                        reject(error)
                    }
                },
                fail: reject
            })
        })
    },
    // 表单验证
    validateForm() {
        const { username, password, studentId, email, phone, avatarUrl } = this.data

        if (!avatarUrl) {
            wx.showToast({
                title: '请上传头像',
                icon: 'none'
            })
            return false
        }

        if (!username.trim()) {
            wx.showToast({
                title: '请输入用户名',
                icon: 'none'
            })
            return false
        }

        if (password.length < 6) {
            wx.showToast({
                title: '密码至少6位',
                icon: 'none'
            })
            return false
        }

        if (!studentId) {
            wx.showToast({
                title: '请输入学号',
                icon: 'none'
            })
            return false
        }

        const emailRegex = /^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/
        if (!emailRegex.test(email)) {
            wx.showToast({
                title: '请输入有效的邮箱',
                icon: 'none'
            })
            return false
        }

        const phoneRegex = /^1[3-9]\d{9}$/
        if (!phoneRegex.test(phone)) {
            wx.showToast({
                title: '请输入有效的手机号',
                icon: 'none'
            })
            return false
        }

        return true
    },
    // 注册处理
    async handleRegister() {
        if (!this.validateForm()) return
        if (this.data.isSubmitting) return

        this.setData({ isSubmitting: true })

        try {
            const res = await new Promise((resolve, reject) => {
                wx.request({
                    url: `${app.globalData.baseUrl}/api/users/register`,
                    method: 'POST',
                    data: {
                        username: this.data.username,
                        password: this.data.password,
                        studentId: this.data.studentId,
                        email: this.data.email,
                        phone: this.data.phone,
                        avatar: this.data.avatarUrl
                    },
                    success: resolve,
                    fail: reject
                })
            })

            if (res.data.success) {
                wx.showToast({
                    title: '注册成功',
                    icon: 'success'
                })

                // 延迟跳转到登录页
                setTimeout(() => {
                    wx.redirectTo({
                        url: '/pages/login/login'
                    })
                }, 1500)
            } else {
                throw new Error(res.data.message || '注册失败')
            }
        } catch (error) {
            console.error('注册失败：', error)
            wx.showToast({
                title: error.message || '注册失败，请重试',
                icon: 'none'
            })
        } finally {
            this.setData({ isSubmitting: false })
        }
    },
    // 跳转到登录页
    goToLogin() {
        wx.navigateTo({
            url: '/pages/login/login'
        })
    }
})